package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * 在进入控制器之前 将userId存进threadLocal以便于各层的调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接受网关传递的userId
        String userId = request.getHeader("userId");
        // 如果userId为空那么它在网关就会被拦截 判空可有可无
        if(StringUtils.isEmpty(userId)){
            log.warn("用户id为空");
            return false;
        }
        //创建WmUser 用来存放userId
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(Integer.parseInt(userId));
        //将WmUser存放进threadLocal
        UserThreadLocal.set(wmUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //属于线程的一个变量  用完删除可以防止内存的溢出
        UserThreadLocal.remove();
    }
}
